package org.duiduo.state;

import java.util.ArrayList;
import java.util.List;

/**
 * 状态机
 *
 * @author liangze
 * @date 2024/2/20 11:40
 */
public class StateMachine {

    // 存储状态信息
    private List<StateTransaction> stateTransactionList;
    // 记录当前状态
    private StateEnum currentState;

    public StateMachine(StateEnum state) {
        currentState = state;
        stateTransactionList = new ArrayList<>();
    }

    // 添加一条状态信息
    public StateTransaction addone() {
        StateTransaction stateTransaction = new StateTransaction();
        stateTransactionList.add(stateTransaction);
        return stateTransaction;
    }

    // 进行状态转移
    public StateTransaction execute(ActionEnum action) {
        for (int i = 0; i < stateTransactionList.size(); i++) {
            if (currentState == stateTransactionList.get(i).getCurrentState() &&
                    action == stateTransactionList.get(i).getAction()) {
                stateTransactionList.get(i).getEvent().handle();
                currentState = stateTransactionList.get(i).getNextState();
                return stateTransactionList.get(i);
            }
        }
        return null;
    }

}
